package br.org.acessobrasil.correiobraille.util;

import java.security.spec.KeySpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.log4j.Logger;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * @author Jonatas Pacheco Ribeiro
 */
public class CbrDES {
	private static Logger logger = Logger.getLogger(CbrDES.class);
	private static BASE64Encoder enc = new BASE64Encoder();
	private static BASE64Decoder dec = new BASE64Decoder();
	
	/**
	 * encripta a mensagem com chave predefinida
	 * 
	 * @param texto
	 * @return msgEncriptada
	 */
	public static String encriptar(String texto, String chave) throws Exception {
		KeySpec ks = new DESKeySpec(chave.getBytes());
		SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
		SecretKey ky = kf.generateSecret(ks);

		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, ky);

		return enc.encode(cipher.doFinal(texto.getBytes()));
	}

	/**
	 * Decripta a mensagem com chave em String
	 * 
	 * @param texto
	 * @param chave
	 * @return mensagem Decriptada
	 */
	public static String decriptar(String texto, String chave) throws Exception {
		String retorno = null;
		KeySpec ks = new DESKeySpec(chave.getBytes());
		SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
		SecretKey ky = kf.generateSecret(ks);

		Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, ky);
		byte[] decoded64 = dec.decodeBuffer(texto);
		logger.debug("decoded64.length = " + decoded64.length);
		logger.debug("%8=" + (decoded64.length%8));
		byte[] decriptado = cipher.doFinal(decoded64);
		retorno = new String(decriptado);
		return retorno;
	}

}
